package org.summerframework.component.security.spring;

import org.summerframework.component.security.events.PermissionsUpdateEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author 石超
 * @version v1.0.0
 */
public class DefaultRoleServiceSupport implements ApplicationListener<PermissionsUpdateEvent> {
    @Resource
    private SecurityRoleService securityRoleService;

    @Resource
    private FindByIndexNameSessionRepository<Session> sessionRepository;

    @Override
    public void onApplicationEvent(PermissionsUpdateEvent event) {
        final Map<String, Session> byIndexNameAndIndexValue = sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, event.getUserId());

        final List<GrantedAuthority> role = securityRoleService.getRole(Long.valueOf(event.getUserId()));

        for (Session session : byIndexNameAndIndexValue.values()) {
            LoginSecurityData loginSecurityData = session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);

            if (loginSecurityData != null) {
                loginSecurityData.setGrantedAuthorities(role);
            }
        }

    }
}
